package util;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public abstract class FileOperations {
	
	private static final int BUFFER_LENGTH = 1024; //1kb

	public static ArrayList<String> readFile(String path) throws IOException {
		ArrayList<String> strings = new ArrayList<String>();
		BufferedReader br;
		
		br = new BufferedReader(new FileReader(path));
		while (br.ready()) {
			strings.add(br.readLine());
		}
		br.close();

		return strings;
	}


	public static void writeFile(String path, ArrayList<String> strings) throws IOException {

		BufferedWriter bw;
		
		createDiretories(path);

		bw = new BufferedWriter(new FileWriter(path));
		bw.write(strings.get(0));
		for (int i = 1; i < strings.size(); i++) {
			bw.newLine();
			bw.write(strings.get(i));
		}
		bw.close();

	}

	public static void writeFile(String path, String string) throws IOException {

		BufferedWriter bw;
		
		createDiretories(path);

		bw = new BufferedWriter(new FileWriter(path));
		bw.write(string);
		bw.close();
	}
	
	public static void zipFiles(String sourcePath, String destinationPath) throws IOException {
		
		FileInputStream inStream;
		ZipOutputStream outStream;
		BufferedOutputStream destination;
		ZipEntry ze;
		byte[] buffer = new byte[BUFFER_LENGTH];
		int bytesRead;

		createDiretories(destinationPath);
			
		//create input and output streams
		inStream = new FileInputStream(sourcePath);
		destination = new BufferedOutputStream(new FileOutputStream(destinationPath));
		outStream = new ZipOutputStream(destination);

		
		//Add a zip entry to the output stream
		String[] nameTable = sourcePath.split("/");
		ze = new ZipEntry(nameTable[nameTable.length-1]);
		outStream.putNextEntry(ze);
		
		while((bytesRead = inStream.read(buffer)) > 0)
			outStream.write(buffer, 0, bytesRead);
		
		outStream.closeEntry();
		outStream.close();
		inStream.close();
			
	}
	
	private static void createDiretories(String destinationPath){
		File f;
		
		String[] path = destinationPath.split("/");
		String folders = "";

		for (int i = 0; i < path.length - 1; i++) {
			folders += path[i] + ((i == path.length - 2) ? "" : "/");
		}
		
		if (!(f = new File(folders)).exists()){
			f.mkdir();
		}
			
	}


}
